package com.startest.sms.web;


import com.startest.sms.entity.dto.Response;
import com.startest.sms.pojo.Permission;
import com.startest.sms.pojo.Role;
import com.startest.sms.pojo.User;
import com.startest.sms.service.UserService;
import com.startest.sms.utils.Constants;
import com.startest.sms.utils.RSAUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/luss/v1/user")
public class UserController {

    @Autowired
    private UserService userService;

    //用户角色分配
    @RequestMapping(value = "/assignRole",method = RequestMethod.POST)
    public Response<String> editUserRole(@RequestParam("userId") Integer userId,
                                         @RequestParam("roleIds") Integer[] roleIds){
        return userService.editUserRole(userId,roleIds);
    }

    //获取角色树
    @RequestMapping(value = "/roleTree",method = RequestMethod.POST)
    public List<Map<String,Object>> getRoleTree(){
        return userService.getRoleTree();
    }

    //获取用户拥有的角色list
    @RequestMapping(value = "/userIdsList",method = RequestMethod.POST)
    public Response<List<Integer>> getRoleIdsByUserId(@RequestParam("userId") Integer userId){
        return userService.getRoleIdsByUserId(userId);
    }

    //删除user
    @RequestMapping(value = "/deleteUser",method = RequestMethod.POST)
    public Response<String> deleteUser(@RequestParam("userId") Integer userId){
        return userService.deleteUser(userId);
    }

    //添加、修改用户
    @RequestMapping(value = "/editUser",method = RequestMethod.POST)
    public Response<String> editUser(User user){
        return userService.editUser(user);
    }

    //查询userList
    @RequestMapping(value = "/userList",method = RequestMethod.POST)
    public List<User> getUserList(){
        return userService.getUserList();
    }

    //删除权限 级联删除相关表中权限信息
    @RequestMapping(value = "/deletePerm",method = RequestMethod.POST)
    public Response<String> deletePerm(@RequestParam("permId") Integer permId){
        return userService.deletePerm(permId);
    }


    //添加、修改权限
    @RequestMapping(value = "/editPerm",method = RequestMethod.POST)
    public Response<String> editPerm(Permission perm){
        return userService.editPerm(perm);
    }

    //获取权限list
    @RequestMapping(value = "/permsList",method = RequestMethod.POST)
    public List<Permission> getPermsList(){
        List<Permission> list = userService.getPermsList();
        return list;
    }

    //删除角色 级联删除相关表中角色信息
    @RequestMapping(value = "/deleteRole",method = RequestMethod.POST)
    public Response<String> deleteRole(@RequestParam("roleId") Integer roleId){
        try {
            userService.deleteRole(roleId);
            return Response.ok("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return Response.fail("删除失败");
        }
    }

    //查询角色拥有的权限list
    @RequestMapping(value = "/permIdsList",method = RequestMethod.POST)
    public Response<List<Integer>> getPermIdsByRoleId(@RequestParam("roleId") Integer roleId){
        try {
            List<Integer> ids = userService.selectPermsByRoleId(roleId);
            return Response.ok(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail("查询权限失败");
        }
    }

    //编辑角色权限
    @RequestMapping(value = "/editRolePerm",method = RequestMethod.POST)
    public Response<String> editRolePerms(@RequestParam("roleId") Integer roleId,
                                          @RequestParam("permIds") Integer[] permIds){
        try {
            userService.editRolePerm(roleId,permIds);
            return Response.ok("编辑成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail("编辑失败");
        }
    }

    //获取权限树
    @RequestMapping(value = "/permsTreeList",method = RequestMethod.POST)
    public List<Permission> getPermsTree(){
        return userService.selectPermList();
    }

    //  添加/修改角色
    @RequestMapping(value = "/editRole",method = RequestMethod.POST)
    public Response<String> editRole(Role role){
        return userService.editRole(role);
    }

    //获取角色信息列表
    @RequestMapping(value = "/roleList")
    public List<Role> getRoleList(){
        return userService.selectRoleList();
    }

    /**
     * RSA生成公钥私钥
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping(value = "/getKey",method = RequestMethod.POST)
    public Object getPublicKey(HttpServletRequest request) throws NoSuchAlgorithmException {
        HashMap<String, String> hashMap = new HashMap<>();
        KeyPair keyPair = RSAUtil.generateKeyPair();

        RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();

        String publicModulus = publicKey.getModulus().toString(16);
        String pulicExponent = publicKey.getPublicExponent().toString(16);
        request.getSession().setAttribute("privkey",privateKey);
        hashMap.put("pubmodulus",publicModulus);
        hashMap.put("pubexponent",pulicExponent);
        return hashMap;
    }

    /**
     * 账号密码注册
     * @param username
     * @param pwd
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Response<String> register(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @RequestParam(value = "username",required = true) String username,
                                     @RequestParam(value = "pwd",required = true) String pwd) throws Exception {
        return userService.addUser(request,response,username,pwd);
    }

    //测试shiro登出
    @RequestMapping(value = "/logouttest",method = RequestMethod.POST)
    public Response<String> logouttest(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Response.ok("操作成功");
    }

    //测试shiro登录
   /* @RequestMapping(value = "/logintest",method = RequestMethod.POST)
    public Response<String> logintest(@RequestParam("username") String username,
                                      @RequestParam("pwd") String pwd){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, pwd);
        try {
            subject.login(token);
            Session session = subject.getSession();
            User user = userService.selectUserByName(username);
            session.setAttribute(Constants.SESSION_USER,user);
            return Response.ok("登录成功");
        }catch (AuthenticationException e){
            e.printStackTrace();
            return Response.fail("登录失败");
        }
    }*/

    //请求获取用户信息
    @RequestMapping(value = "/account",method = RequestMethod.POST)
    public Response<String> getAccount(){
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String username = (String) session.getAttribute(Constants.USER_ID);
        return Response.ok(username);
    }

    /**
     * 账号密码登录
     * @param request
     * @param response
     * @param username
     * @param pwd
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Response<String> login(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "username",required = true) String username,
                                  @RequestParam(value = "pwd",required = true) String pwd,
                                  @RequestParam(value = "autoLogin",required = false) String autoLogin) throws Exception {
        return userService.login(request,response,username,pwd,autoLogin);
    }

    /**
     * 发送手机验证码
     * @param phone
     * @param request
     * @return
     */
    @RequestMapping(value = "/codesend",method = RequestMethod.POST)
    public Response<String> sendSMS(@RequestParam(value = "phone",required = true) String phone,
                                    HttpServletRequest request){
        return userService.sendSMS(phone,request);
    }

    /**
     * 手机登录
     * @param phone
     * @param code
     * @param request
     * @return
     */
    @RequestMapping(value ="/phonelogin",method = RequestMethod.POST)
    public Response<String> phoneLogin(@RequestParam("phone") String phone,
                                       @RequestParam("code") String code,
                                       HttpServletRequest request){
        return userService.phoneLogin(phone,code,request);
    }

    /**
     * 手机注册
     * @param phone
     * @param code
     * @param request
     * @return
     */
    @RequestMapping(value ="/phoneReg",method = RequestMethod.POST)
    public Response<String> phoneRegister(@RequestParam("phone") String phone,
                                          @RequestParam("code") String code,
                                          HttpServletRequest request){
        return userService.phoneReg(phone,code,request);
    }

    /**
     * 邮箱注册
     * @param username
     * @param pwd
     * @param email
     * @return
     */
    @RequestMapping(value = "/emailReg",method = RequestMethod.POST)
    public Response<String> emailRegister(@RequestParam(value = "username") String username,
                                          @RequestParam(value = "pwd") String pwd,
                                          @RequestParam(value = "email") String email,
                                          HttpServletRequest request) throws Exception{
        return userService.emailReg(username,pwd,email,request);
    }

    /**
     * 邮箱激活
     * @param code
     * @return
     */
    @RequestMapping(value = "/emailActive",method = RequestMethod.GET)
    public Response<String> emailCheck(@RequestParam(value = "code") String code){
        return userService.emailCheck(code);
    }

}
